//
//  JXChatCtl.m
//  JiaoX
//
//  Created by yinqy on 15/3/11.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "JXChatCtl.h"
#import "JXReplyCommentView.h"
#import "JXMessage.h"
#import "JXChatManager.h"
#import "ChatCell.h"
#import "UserInfoDao.h"
#import "JXUserInfoCtl.h"
#import "ForumDataTool.h"
#import "MJRefresh.h"
#import "EmotionKeyboard.h"

@interface JXChatCtl()<UITableViewDelegate,UITableViewDataSource,JXReplyCommentViewDelegate,JXChatManagerDelegate,SendFileKeyboardDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)JXReplyCommentView *replyView;
@property (nonatomic, strong)UserInfo *chatUserInfo;
@property (nonatomic, strong)NSMutableArray *chatCellFrames;
@property (nonatomic, strong)NSMutableDictionary *userInfoDic;
@property (nonatomic, strong)UserInfoDao *userInfoDao;
@property (assign, nonatomic, readonly) UIEdgeInsets originalTableViewContentInset;
@property (nonatomic, assign)RoomType *roomType;
@end

@implementation JXChatCtl

-(instancetype)initWithUserInfo:(UserInfo *)userInfo
{
    self = [super init];
    if (self) {
        self.chatUserInfo = userInfo;
        self.roomType = RoomTypeSingle;
    }
    return self;
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:self.chatUserInfo.nickName];
    
    _chatCellFrames = [[NSMutableArray alloc]init];
    _userInfoDic = [NSMutableDictionary dictionary];
    _userInfoDao = [[UserInfoDao alloc]init];
    [_chatCellFrames addObjectsFromArray:[self messagesConvertToFrame:[[JXChatManager sharedInstance].chatMsgDao getMsgsWithUserId:self.chatUserInfo.userId timestamp:nil number:20]]];
    [self setAutomaticallyAdjustsScrollViewInsets:NO];
    [self setUpView];
    
    //设置与这个人的未读消息都为已读
    [[JXChatManager sharedInstance].chatMsgDao setMessageReadStatus:self.chatUserInfo.userId];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMessageCome:) name:NOTI_NEW_MESSAGE object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"ic_chat_user" highImageName:@"ic_chat_user_heighlight" target:self action:@selector(report)];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self scrollToBottomAnimated:NO];
    _originalTableViewContentInset = self.tableView.contentInset;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillShowKeyboard:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleWillHideKeyboard:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [self setEditing:NO animated:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)setUpView{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, NavHeight, JXScreenW,JXScreenH-49-NavHeight)];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView addHeaderWithTarget:self action:@selector(headerRefresh)];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView hiddenHeaderTimeLabel];
    [_tableView setHeaderPullToRefreshText:@"查看更多"];
    [_tableView setHeaderRefreshingText:@"正在加载"];
    [_tableView setHeaderReleaseToRefreshText:@"查看更多"];
    

    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyboard)];
    [self.tableView addGestureRecognizer:gestureRecognizer];
    [self.tableView addGestureRecognizer:swipe];
    
    [self.view addSubview:_tableView];
    
    _replyView = [[JXReplyCommentView alloc]initWithPlaceholder:@"聊聊嘛"];
    _replyView.x = 0;
    _replyView.y = self.view.height-49;
    _replyView.delegate = self;
    _replyView.fileKeyboard.delegate = self;
    [_replyView setShowEmotion:YES];
    [self.view addSubview:_replyView];
    
    [JXChatManager sharedInstance].delegate = self;
}

#pragma mark - tableviewdelegate

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.chatCellFrames.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatCell *cell = [ChatCell cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ChatCellViewFrame *frame = self.chatCellFrames[indexPath.row];
    [cell setCellViewFrame:frame];
    NSString *userId = frame.message.fromPeerId;
    [cell.chatCellView setUserinfo:[self getUserInfoWithUserId:userId]];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    ChatCellViewFrame *frame = self.chatCellFrames[indexPath.row];
    return frame.frame.size.height;
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self hideKeyboard];
}

#pragma mark - 输入框的delegate
- (void)bottomViewReplyBtnClick:(NSString *)replyContent{
    if ([self isCanChat:replyContent]) {
        [self sendMessageWithContent:replyContent];
    }
}

-(void)sendMessageWithContent:(NSString *)content{
    if (self.chatCellFrames.count == 0 && self.roomType == RoomTypeSingle) {
        if (![_userInfoDao getUserInfoWithId:self.chatUserInfo.userId]) {
            [_userInfoDao setUserInfo:self.chatUserInfo];
        }
    }
    [[JXChatManager sharedInstance].chatMsgDao addSessionWithId:self.chatUserInfo.userId type:RoomTypeSingle];
    
    //发送消息，并把消息更新到界面上
    JXMessage *message = [[JXChatManager sharedInstance] sendMessageToPeerId:[NSString stringWithFormat:@"%@",self.chatUserInfo.userId] messageStr:content];
    [self updateUIWithMessage:message];
    
}

#pragma mark - 发送文件键盘的代理;
-(void)sendFileWithData:(NSData *)data{
    //在这处理发送图片的逻辑
    //1.将图片保存在本地
    
    //生成messageId
    NSString *messageId = [NSString randomStringWithLength:24];
    //通过messageid生成文件路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:messageId];
    NSLog(@"filePath=%@",filePath);
    //保存文件
    [data writeToFile:filePath atomically:YES];
    
    UIImage *image = [UIImage imageWithData:data];
    
    //上传图片，保存数据库
    JXMessage *message = [[JXChatManager sharedInstance] imgMsgWithObjectId:messageId imgFile:filePath toPeerId:self.chatUserInfo.userId imgW:image.size.width imgH:image.size.height];
    //更新ui
    [self updateUIWithMessage:message];
}

-(void)updateUIWithMessage:(JXMessage *)message{
    ChatCellViewFrame *frame = [[ChatCellViewFrame alloc]init];
    int64_t timestamp = 0;
    if ([self.chatCellFrames lastObject]) {
        ChatCellViewFrame *lastFrame = [self.chatCellFrames lastObject];
        timestamp = lastFrame.message.timestamp;
    }
    [frame setMessage:message preTimestamp:timestamp];
    
    [self.chatCellFrames addObject:frame];
    [self.tableView reloadData];
    [self scrollToBottomAnimated:YES];
    [self.replyView setText:nil];
}

#pragma mark - chatmanager delegate
-(void)newMessageCome:(NSNotification *)noti{
    NSDictionary *dic = noti.object;
    JXMessage *message = [dic valueForKey:@"message"];
    MsgUpdateType type = [[dic valueForKey:@"MsgUpdateType"] integerValue];
    [self messageUpdate:message msgUpdateType:type];
}

-(void)messageUpdate:(JXMessage *)message msgUpdateType:(MsgUpdateType)type{
    if ([message.toPeerId longLongValue]== [_chatUserInfo.userId longLongValue]
        ||[message.fromPeerId longLongValue] == [_chatUserInfo.userId longLongValue]) {
        
        if (type==MsgUpdateTypeReceive) {
            [self updateUIWithMessage:message];
            //是别人发过来的消息
            [[JXChatManager sharedInstance].chatMsgDao setMessageReadStatus:self.chatUserInfo.userId];
        }
    }
}
#pragma mark - 私有方法
/**
 * 是否可以聊天
 */
-(BOOL)isCanChat:(NSString *)content{
    NSString *canChat = [UserDefaultsHelper stringForKey:KEY_CHAT_ENABLE];
    if (![Utils isBlankString:canChat]) {
        [ForumDataTool getChatSignatureWithAppId:LEANCLOUD_APPID peerId:[UserDefaultsHelper stringForKey:KEY_USER_ID] success:^(ChatSignature *result) {
            if (result.code==0) {
                [[JXChatManager sharedInstance] openSession];
                [UserDefaultsHelper setObject:result.canSend forKey:KEY_CHAT_ENABLE];
                if (![Utils isBlankString:result.canSend]) {
                    [self hideKeyboard];
                    [DialogUtils showTipsWithView:self.navigationController.view String:result.canSend];
                }else{
                    [self sendMessageWithContent:content];
                }
            }
        } failure:^(NSError *error) {
            
        }];
        return NO;
    }
    return YES;
}


-(void)headerRefresh{
    //去加载更多聊天记录
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *timestamp = nil;
        
        if (_chatCellFrames.count) {
            ChatCellViewFrame *frame = [_chatCellFrames firstObject];
            timestamp = [NSString stringWithFormat:@"%lld",frame.message.timestamp];
        }
        
        NSArray *array = [self messagesConvertToFrame:[[JXChatManager sharedInstance].chatMsgDao getMsgsWithUserId:self.chatUserInfo.userId timestamp:timestamp number:20]];
        if (array.count) {
            if (_chatCellFrames.count) {
                ChatCellViewFrame *frame = _chatCellFrames.firstObject;
                ChatCellViewFrame *preframe = array.lastObject;
                [frame setMessage:frame.message preTimestamp:preframe.message.timestamp];
            }
            [_chatCellFrames insertObjects:array atIndexes:[NSIndexSet indexSetWithIndexesInRange:
                                                            NSMakeRange(0,[array count])]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [Utils refreshComplete:self.tableView];
            [self.tableView reloadData];
        });
    });
    
}
-(void)hideKeyboard{
    [self.replyView resetKeyBoard];
    [self.view endEditing:YES];
}

-(UserInfo *)getUserInfoWithUserId:(NSString *)userId{
    UserInfo *userInfo = [_userInfoDic valueForKey:[NSString stringWithFormat:@"%@",userId]];
    if (userInfo) {
        return userInfo;
    }else{
        userInfo = [_userInfoDao getUserInfoWithId:userId];
        if (userInfo==nil && [userId isEqualToString:CURRENTUSERID]) {
            userInfo = [Utils currentUserInfo];
            [_userInfoDao setUserInfo:userInfo];
        }
        [_userInfoDic setObject:userInfo forKey:userId];
        return userInfo;
    }
}

- (NSArray *)messagesConvertToFrame:(NSArray *)messages{
    NSMutableArray *frames = [NSMutableArray array];
    for (int i= 0; i<messages.count; i++) {
        int64_t preTimestame = 0;
        if (i!=0) {
            JXMessage  *preMsg = messages[i-1];
            preTimestame =preMsg.timestamp;
        }
        
        ChatCellViewFrame *frame = [[ChatCellViewFrame alloc]init];
        [frame setMessage:messages[i] preTimestamp:preTimestame];
        [frames addObject:frame];
    }

    return frames;
}

- (void)scrollToBottomAnimated:(BOOL)animated
{
    NSInteger rows = [self.tableView numberOfRowsInSection:0];
    if(rows > 0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:rows - 1 inSection:0]
                              atScrollPosition:UITableViewScrollPositionBottom
                                      animated:animated];
    }
}

-(void)report{
    JXUserInfoCtl *ctl = [[JXUserInfoCtl alloc]initWithUserId:self.chatUserInfo.userId];
    [self.navigationController pushViewController:ctl animated:YES];
//    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:@"言论涉及色情、暴力、广告等方可举报\n举报后对方将被禁言，请勿随便举报" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//    [alert show];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [ForumDataTool reportUserWithUserId:self.chatUserInfo.userId success:^(JXBaseResponse *result) {
            if ([Utils isBlankString:result.data]) {
                [DialogUtils showTipsWithView:self.navigationController.view String:@"举报成功"];
            }else{
                [DialogUtils showTipsWithView:self.navigationController.view String:result.data];
            }
        } failure:^(NSError *error) {
            [DialogUtils showTipsWithView:self.navigationController.view String:@"举报失败"];
        }];
    }
}

#pragma mark - Keyboard notifications
- (void)handleWillShowKeyboard:(NSNotification *)notification
{
    [self keyboardWillShowHide:notification show:YES];
}

- (void)handleWillHideKeyboard:(NSNotification *)notification
{
    [self keyboardWillShowHide:notification show:NO];
}

- (void)keyboardWillShowHide:(NSNotification *)notification show:(BOOL)ssssss
{
    CGRect keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    double duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:duration
                          delay:0.0f
                        options:[UIView animationOptionsForCurve:curve]
                     animations:^{
                         CGFloat keyboardY = [self.view convertRect:keyboardRect fromView:nil].origin.y;
                         
                         CGRect inputViewFrame = self.replyView.frame;
                         CGFloat inputViewFrameY = keyboardY - inputViewFrame.size.height;
                         
                         CGFloat messageViewFrameBottom = self.view.frame.size.height - self.replyView.height;
                         if(inputViewFrameY > messageViewFrameBottom)
                             inputViewFrameY = messageViewFrameBottom;
                         
                         self.replyView.frame = CGRectMake(inputViewFrame.origin.x,
                                                                  inputViewFrameY,
                                                                  inputViewFrame.size.width,
                                                                  inputViewFrame.size.height);
                         UIEdgeInsets insets = self.originalTableViewContentInset;
                         insets.bottom = self.view.frame.size.height - self.replyView.frame.origin.y - inputViewFrame.size.height;
                         
                         self.tableView.contentInset = insets;
                         self.tableView.scrollIndicatorInsets = insets;
                         [self scrollToBottomAnimated:YES];

                     }
                     completion:^(BOOL finished) {
                         
                     }];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:NOTI_NEW_MESSAGE object:nil];
    //取消watch用户
    [[JXChatManager sharedInstance] unWatchWithPeerId:self.chatUserInfo.userId];
}

@end
